<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
        addPermi: ['business:camera:add'],
      }"
      :table-props="{
        selection: true,
        delBtn: true,
        viewBtn: false,
        editBtn: true,
        menuSlot: true,
        menuWidth: 300,
        viewPermi: ['business:camera:query'],
        editPermi: ['business:camera:edit'],
        delPermi: ['business:camera:delete'],
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #menuSlot></template>
      <template #online="scope:any">
        <DictTag :options="OnlineStatusEnum" :value="scope.row.online" />
      </template>

      <template #priceId="scope:any">
        {{scope.row.price ? scope.row.price.name : '-'}}
      </template>

      <template #status="scope:any">
        <el-switch
          v-has-permi="['business:camera:edit']"
          v-model="scope.row.status"
          active-value="Enabled"
          inactive-value="Disabled"
          @change="handleStatusChange(scope.row)"
        />
        <DictTag v-has-no-permi="['business:camera:edit']" :options="EnableStatusEnum" :value="scope.row.status" />
      </template>
    </yt-crud>
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { ComponentInternalInstance } from 'vue'
import {
  cameraList,
  cameraSave,
  cameraDelete,
  cameraBatchDelete,
  changeStatus
} from '@/api/business/camera'
import {optionSelect as productOptionSelect} from '@/api/platform/product'
import {ProductsVo} from '@/api/platform/product/types'

import YtCrud from '@/components/common/yt-crud.vue'
import {StationVo} from '@/api/business/station/types'
import {optionSelect as stationOptionSelect } from '@/api/business/station'
import {useI18n} from 'vue-i18n'

const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum, OnlineStatusEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum', 'online_status_enum'))

const productOptions = ref<ProductsVo[]>([])
const stationOptions = ref<StationVo[]>([])

const formProps = ref({
  width: 600,
})

const state = reactive({
  page: {
    pageSize: 30,
    pageNum: 1,
    sortMap: { name: 'asc', createTime: 'desc'},
  },
  total: 0,
  loading: false,
  query: {},
})


const column = ref<IColumn[]>([
  {
    label: t('business.camera.productKey'),
    key: 'productKey',
    type: 'select',
    sortable: false,
    search: false,
    editHide: true,
    colSpan: 22,
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'productKey',
      options: [],
    },
    rules: [{ required: true, message: t('business.camera.validator.productKey') }],
  },
  {
    label: t('business.camera.name'),
    key: 'name',
    sortable: true,
    componentProps: {
      placeholder: t('business.camera.placeholder.name'),
    },
    rules: [{ required: true, message: t('business.camera.validator.name') }],
  },
  {
    label: t('business.camera.dn'),
    key: 'dn',
    sortable: true,
    componentProps: {
      placeholder: t('business.camera.placeholder.dn'),
    },
    rules: [{ required: true, message: t('business.camera.validator.dn') }],
  },
  {
    label: t('business.camera.stationId'),
    key: 'stationId',
    search: true,
    sortable: false,
    type: 'i18nSelect',
    slot: false,
    formHide: false,
    colSpan: 22,
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'id',
      options: [],
    },
    rules: [{ required: true, message: t('business.camera.validator.stationId') }],
  },
  {
    label: t('business.camera.online'),
    key: 'online',
    type: 'select',
    componentProps: {
      options: OnlineStatusEnum,
    },
    search: true,
    formHide: true,
    sortable: false,
    slot: true,
  },
  {
    label: t('business.camera.status'),
    key: 'status',
    type: 'select',
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: true,
    sortable: false,
    slot: true,
    rules: [{ required: true, message: t('business.camera.validator.status') }],
  },
  {
    label: t('business.camera.note'),
    key: 'note',
    hide: true,
    formHide: false,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  cameraList({
    ...state.page,
    ...state.query,
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

const getDict = () => {
  productOptionSelect({ type: 'Dcam', status: 'Enabled' }).then((res) => {
    productOptions.value = res.data || []
    column.value.forEach((item) => {
      if (item.key === 'productKey') {
        item.componentProps.options = productOptions.value.map((item)=> {
          return {productKey: item.productKey, name: item.name}
        })
      }
    })
  })

  stationOptionSelect({ status: 'Enabled' }).then((res) => {
    stationOptions.value = res.data || []
    column.value.forEach((item) => {
      if (item.key === 'stationId') {
        item.componentProps.options = stationOptions.value.map((item)=> {
          return {id: item.id, name: item.name}
        })
      }
    })
  })
}
getDict()

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  await cameraSave(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}
// 弹窗前置操作
const openBeforeFun = ({ type }) => {
  if (type === 'add') { /* empty */ } else if (type === 'update') { /* empty */ }
}

/** 状态修改  */
const handleStatusChange = async (row: any) => {
  if(!row.id)  return
  try {
    await proxy?.$modal.confirm(row.status === 'Enabled' ? t('crud.action.tooltip.enable') : t('crud.action.tooltip.disabled'))
    await changeStatus(row.id, row.status)
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  } catch (err) {
    row.status = row.status === 'Enabled' ? 'Disabled' : 'Enabled'
  }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    cameraBatchDelete(row.map((m) => m.id)).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  } else {
    cameraDelete(row.id).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  }
}


const multipleSelection = ref<{ id: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}


const options = reactive({
  ref: 'crudRef',
  formProps,
  data,
  column,
})
</script>
